package com.helloworld.demo.atomic;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

public class ThreadAtomicIntegerFieldUpdaterTest {

    public static class Candidate {
        //属性修改器处理的字段必须是volatile修饰的
        volatile int score = 0;

        AtomicInteger score2 = new AtomicInteger();
    }

    static AtomicIntegerFieldUpdater<Candidate> scoreUpdater = AtomicIntegerFieldUpdater.newUpdater(Candidate.class,"score");
    static AtomicInteger realScore = new AtomicInteger(0);


    public static void main(String[] args) throws InterruptedException {
        Candidate candidate = new Candidate();
        Thread[] threads = new Thread[10000];
        for(int i = 0;i < threads.length;i++){
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    if(Math.random() > 0.4){
                        candidate.score2.incrementAndGet();
                        scoreUpdater.incrementAndGet(candidate);
                        realScore.incrementAndGet();
                    }
                }
            });
            threads[i].start();
        }

        for (int i = 0;i < threads.length;i++){
            threads[i].join();
        }

        System.out.println("AtomicIntegerFieldUpdater.score：" + candidate.score);
        System.out.println("candidate.score2：" + candidate.score2);
        System.out.println("AtomicInteger.realScore：" + realScore.get());
    }

}
